import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from './store/modules/user'
import pinia from './store'
import setting from './setting'
let userStore = useUserStore(pinia)

router.beforeEach(async (to: any, from: any, next: any) => {
  // to and from are both route objects. must call `next`.
  nprogress.start()
  let token = userStore.token
  let username = userStore.username
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        try {
          //获取用户信息
          await userStore.userInfo()
          next({ ...to })
        } catch (error) {
          //token过期
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
          // console.log(to.path);

        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

router.afterEach((to: any, from: any) => {
  // to and from are both route objects.
  nprogress.done()
  document.title = setting.title + ' - ' + to.meta.title
})